// eslint-disable-next-line
import * as loginService from '@/api/login'
// eslint-disable-next-line
import {
  BasicLayout,
  BlankLayout,
  PageView,
  RouteView
} from '@/layouts'

// 前端路由表
const constantRouterComponents = {  
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  '403': () => import( /* webpackChunkName: "error" */ '@/views/exception/403'),
  '404': () => import( /* webpackChunkName: "error" */ '@/views/exception/404'),
  '500': () => import( /* webpackChunkName: "error" */ '@/views/exception/500'),

  // 'MenuSetting': () => import('@/views/userSetting/MenuSetting'),
  // 'UserList': () => import('@/views/userSetting/UserList'),
  // 'RoleList': () => import('@/views/userSetting/RoleList'),
  'dashboard': () => import('@/views/dashboard/Dashboard'),
  // 'Deparment': () => import('@/views/userSetting/Deparment'),
  
  // 'ModalSetting': () => import('@/views/systemSetting/ModalSetting'),
  // 'DictionarySetting': () => import('@/views/setting/DictionarySetting'),
  // 'ProjectAdd': () => import('@/views/projectReport/ProjectAdd'),
  // 'ProjectEdit': () => import('@/views/projectReport/ProjectEdit'),
  // 'ProjectApprove': () => import('@/views/projectReport/ProjectApprove'),
  // 'ProjectChAdd': () => import('@/views/projectReport/ProjectChAdd'),
  // 'ProjectChBrowse': () => import('@/views/projectReport/ProjectChBrowse'),
  // 'ProjectCompliance': () => import('@/views/projectReport/ProjectCompliance'),
  // 'ProjectProgress': () => import('@/views/projectReport/ProjectProgress'),
  // 'ProjectWarning': () => import('@/views/projectReport/ProjectWarning'),
  // 'Budget': () => import('@/views/projectFunds/Budget'),
  
}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true
}

// 根级菜单
const rootRouter = {
    key: '',
    path: '/',
    name: 'index',
    component: 'BasicLayout',
    meta: { title: '首页',  permission: [ 'table' ] },
    redirect: '',
  children: []
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (token) => {
  return new Promise((resolve, reject) => {
    loginService.getCurrentUserNav(token).then(res => {
      console.log('res', res)
      const {
        result
      } = res
      const menuNav = []
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      listToTree(result, childrenNav, 0)
      rootRouter.children = childrenNav
   
       console.log('mainpage', mainpage)
      menuNav.push(rootRouter)
      console.log('menuNav', menuNav)
      const routers = generator(menuNav)

      const mainpage = getMainpage(routers)
      routers[0].redirect = mainpage
      routers.push(notFoundRouter)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const currentRouter = {
      // 路由地址 动态拼接生成如 /dashboard/workplace
      path: `${parent && parent.path || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
       leaf: item.leaf || '',
      // 该路由对应页面的 组件
      // component: constantRouterComponents[item.component || item.key],
      
      component: (constantRouterComponents[item.component || item.key]) || (() => import(`@/views${parent && parent.path || ''}/${item.key}`) ),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: { title: item.title, icon: item.icon || undefined, 
      keepAlive: true,
       permission: item.key && [ item.key ] || null },
      //permission: 'table' }
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    currentRouter.path = currentRouter.path.replace('//', '/')
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: item.children
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
/**
 * 动态获取主页
 * @param token
 * @returns {Promise<Router>}
 */
 const getMainpage = ( childrenNav) => {
   var val = ''
   for(var i = 0; i < childrenNav.length; i ++){
     var item  = childrenNav[i]
     if (item.leaf == 1) {
        return item.path
     }else{
        return getMainpage(item.children)
     }
   }
   // return val
  }